#include "GameMap.h"
typedef enum TILE_LIST {
    T_GRASS = 1,
    T_SAND,
    T_WATER
} TILE_LIST;
GameMap::GameMap()
{
    //map_surf = NULL;
    tmx_tmp = (char*)load_file("untitled.tmx",true);
    xml_map = NLLoadTmxMap( tmx_tmp );
    pop_arry();
    //ctor
}

GameMap::~GameMap()
{
    //SDL_FreeSurface(map_surf);
    delete xml_map;
    //dtor
}
void* GameMap::load_file(const char* file_name, bool appendNull) {

    FILE* f = fopen( file_name, "r" );
    if ( !f ) {
        return 0;
    }

    fseek( f, 0, SEEK_END );
    auto length = ftell( f ) + appendNull;
    fseek( f, 0, SEEK_SET );

    void* buffer = malloc( length );
    fread( buffer, length, 1, f );
    fclose( f );

    if ( appendNull ) {
        ((char*)buffer)[ length-1 ] = 0;
    }

    return buffer;

}
void GameMap::print(){
    for(int i = 0; i < M_ROWS; i++) {
        for(int j = 0; j < M_COLS; j++) {
            std::cout << map_data[i][j] << " ";

        }
        std::cout << std::endl;

    }
}
void GameMap::pop_arry(){
    int index = 0;

    for(int i = 0; i < M_ROWS; i++) {
        for(int j = 0; j < M_COLS; j++) {
            map_data[i][j] = xml_map->layers[0]->data[index];
            index++;
        }


    }

}
int GameMap::get_tile_data(int row_val, int col_val) {
    return map_data[row_val][col_val];
}
int** GameMap::get_tile_set() {
    return (int**)&map_data;
}
void GameMap::draw(SDL_Surface* screen) {
    SDL_Surface* tmp_surf = NULL;
    SDL_Rect offset;
    offset.x = offset.y = 0;

    for(int i = 0; i < M_ROWS; i++) {
        offset.x = 0;
        for(int j = 0; j < M_COLS; j++) {
                switch(map_data[i][j]) {
                case T_GRASS:
                    tmp_surf = image_load("grass.png");
                    break;
                case T_SAND:
                   tmp_surf = image_load("sand.png");
                   break;
                case T_WATER:
                    tmp_surf = image_load("water.png");
                    break;
                default: break;
            }
            SDL_BlitSurface(tmp_surf, NULL, screen, &offset);
            offset.x += 20;
        }
        offset.y += 20;
    }
    SDL_SaveBMP(screen, "background.bmp");
    SDL_FreeSurface(tmp_surf);
}
SDL_Surface* GameMap::image_load(std::string file_name) {
    SDL_Surface* loaded = NULL;
    SDL_Surface* optoed = NULL;
    loaded = IMG_Load(file_name.c_str());
    if(loaded != NULL) {
        optoed = SDL_DisplayFormatAlpha(loaded);
        SDL_FreeSurface(loaded);
    }
    return optoed;
}
